package com.shijunhao.graduation.service.business.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.shijunhao.graduation.domain.dto.BusinessForumTypeDto;
import com.shijunhao.graduation.domain.entity.BusinessForumThyme;
import com.shijunhao.graduation.domain.entity.BusinessForumType;
import com.shijunhao.graduation.domain.vo.BusinessForumThymeVo;
import com.shijunhao.graduation.domain.vo.BusinessForumTypeVo;
import com.shijunhao.graduation.exception.BusinessException;
import com.shijunhao.graduation.mapper.BusinessForumTypeMapper;
import com.shijunhao.graduation.service.business.IBusinessForumThymeService;
import com.shijunhao.graduation.service.business.IBusinessForumTypeService;
import com.shijunhao.graduation.service.system.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author shijunhao
 * @since 2022-04-16
 */
@Service
public class BusinessForumTypeServiceImpl extends BaseServiceImpl<BusinessForumTypeMapper, BusinessForumType> implements IBusinessForumTypeService {

    @Resource
    private IBusinessForumThymeService businessForumThymeService;

    @Override
    public Long insert(BusinessForumTypeDto dto) {
        BusinessForumType entity = new BusinessForumType();
        BeanUtils.copyProperties(dto, entity);
        boolean b = this.insertOne(entity);
        if (!b)
            throw new BusinessException("添加失败");
        return entity.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(BusinessForumTypeDto dto) {
        BusinessForumType byId = getById(dto.getId());
        BeanUtils.copyProperties(dto,byId);
        return updateById(byId);
    }

    @Override
    public List<BusinessForumTypeVo> listAll() {
        List<BusinessForumType> businessForumTypes = this.selectByCondition(Wrappers.lambdaQuery(BusinessForumType.class));
        return businessForumTypes.stream().map(this::toVo).collect(Collectors.toList());
    }

    @Override
    public BusinessForumTypeVo toVo(BusinessForumType entity) {
        BusinessForumTypeVo result = new BusinessForumTypeVo();
        BeanUtils.copyProperties(entity, result);
        //获取主题信息
        List<BusinessForumThyme> businessForumThymes = businessForumThymeService.listByCondition(Wrappers.lambdaQuery(BusinessForumThyme.class).eq(BusinessForumThyme::getForumTypeId, entity.getId()));
        List<BusinessForumThymeVo> thymeVos = businessForumThymes.stream().map(businessForumThymeService::toVo).collect(Collectors.toList());
        result.setThymes(thymeVos);
        return result;
    }
}
